package org.example.bio;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

/**
 * <p> 时间服务器 Handler </p>
 *
 * @author Chris
 * @since 2024/3/23 13:24
 */
public class TimeServerHandler implements Runnable {
    /**
     * 使用 slf4j 日志框架
     */
    private final static Logger log = LoggerFactory.getLogger(TimeServerHandler.class);

    private final Socket socket;

    public TimeServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (final BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
             final PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true)) {

            while (true) {
                String body = in.readLine();
                if (StringUtils.isBlank(body)) {
                    break;
                }

                log.info("The time server receive order : " + body);

                final String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body)
                        ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
                out.println(currentTime);
            }

        } catch (IOException e) {
            log.error("", e);
        }
    }

}